/*
 * ttbqt - A teletekst browser
 * http://code.google.com/p/ttbqt
 * Copyright (C) 2011, Kevin van der Vlist
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * Thanks to Hetwieg for providing the 'documentation'
 */

#include "TSSView.h"

typedef unsigned char byte;

#include <QDebug>

TSSView::TSSView(QString fontfile) {
  qnam = new QNetworkAccessManager(this);

  QObject::connect(qnam, SIGNAL(finished(QNetworkReply*)), this, SLOT(fontFileFinished(QNetworkReply*)));

  QNetworkRequest request;
  request.setUrl(QUrl(fontfile));
  request.setRawHeader("User-Agent", USER_AGENT);
  qnam->get(request);
}

TSSView::~TSSView() {
  delete qnam;
}

QPixmap *TSSView::getPixmap(QByteArray *page) {
  // The byte location. First 2 bytes (0,1) are padding
  int bloc = 2;
  // The header is 5 bytes
  QByteArray header = page->mid(bloc, 5);
  bloc+=5;
  // Pageno is 2 bytes:
  int pg_no = page->at(bloc++) + (page->at(bloc++) << 8);

  return new QPixmap();
}

/**
 * \short Slot function for a finished download
 * 
 * \param p Pointer to the QNetworkReply
 * 
 * Set the pixpage to the downloaded image. 
 * This function needs to be overridden if the download is not an image. 
 */

void TSSView::fontFileFinished(QNetworkReply* reply) {
  qDebug() << "fontFileFinished() - url: " << reply->request().url();
  fontfile = new QImage();
  if (reply->error() == QNetworkReply::NoError) {
    // Valid reply
    fontfile->load(reply, 0);
    if (!fontfile->isNull()) {
      qDebug() << "fontFileFinished(): OK";
    }
  }
  else {
    // Page not found
      qDebug() << "fontFileFinished(): ERR";
  }
  reply->deleteLater();
}
